/*
 * Copyright 2007-2008 Sun Microsystems, Inc.  All Rights Reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Sun designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Sun in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
 * CA 95054 USA or visit www.sun.com if you need additional information or
 * have any questions.
 */

package jsr203.sun.nio.fs;

import java.io.IOException;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.ArrayList;
import java.util.Properties;
import jsr203.nio.file.FileRef;
import jsr203.nio.file.FileStore;
import jsr203.nio.file.Path;
import jsr203.nio.file.ProviderMismatchException;
import jsr203.nio.file.attribute.FileStoreAttributeView;
import jsr203.nio.file.attribute.FileStoreSpaceAttributeView;
import jsr203.nio.file.attribute.FileStoreSpaceAttributes;

/**
 * Base implementation of FileStore for Unix/like implementations.
 */

abstract class UnixFileStore
    extends FileStore
{
    // original path of file that identified file system
    private final UnixPath file;

    // device ID
    private final long dev;

    // entry in the mount tab
    private final UnixMountEntry entry;

    UnixFileStore(UnixPath file) throws IOException {
        // need device ID
        long devID = 0;
        try {
            devID = UnixFileAttributes.get(file.getPathForSysCalls(), true).dev();
        } catch (UnixException x) {
            x.rethrowAsIOException(file);
        }
        this.file = file;
        this.dev = devID;
        this.entry = findMountEntry(file.getFileSystem());
    }

    UnixFileStore(UnixFileSystem fs, UnixMountEntry entry) {
        this.file = new UnixPath(fs, entry.dir());
        this.dev = entry.dev();
        this.entry = entry;
    }

    /**
     * Find the mount entry for this file system
     */
    abstract UnixMountEntry findMountEntry(UnixFileSystem fs) throws IOException;

    UnixPath file() {
        return file;
    }

    long dev() {
        return dev;
    }

    UnixMountEntry entry() {
        return entry;
    }

    @Override
    public String name() {
        return entry.name();
    }

    @Override
    public String type() {
        return entry.fstype();
    }

    @Override
    public boolean isReadOnly() {
        return entry.isReadOnly();
    }

    @Override
    @SuppressWarnings("unchecked")
    public Iterable<Class<? extends FileStoreAttributeView>> getFileStoreAttributeViews()
    {
        ArrayList list = new ArrayList();
        list.add(FileStoreSpaceAttributeView.class);
        return list;
    }

    @Override
    @SuppressWarnings("unchecked")
    public <V extends FileStoreAttributeView> V newFileStoreAttributeView(Class<V> viewType)
    {
        if (viewType == FileStoreSpaceAttributeView.class) {
            return (V) new UnixFileStoreAttributeView().bind(this);
        }
        return (V) null;
    }

    @Override
    public boolean equals(Object ob) {
        if (ob == this)
            return true;
        if (!(ob instanceof UnixFileStore))
            return false;
        UnixFileStore other = (UnixFileStore)ob;
        return dev == other.dev;
    }

    @Override
    public int hashCode() {
        return (int)(dev ^ (dev >>> 32));
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder(new String(entry.dir()));
        sb.append(" (");
        sb.append(entry.name());
        sb.append(")");
        return sb.toString();
    }

    private static class UnixFileStoreAttributeView
        implements FileStoreSpaceAttributeView
    {
        private volatile UnixFileStore obj;

        @Override
        public UnixFileStoreAttributeView bind(FileStore obj) {
            if (obj != null && !(obj instanceof UnixFileStore))
                throw new ProviderMismatchException();
            this.obj = (UnixFileStore)obj;
            return this;
        }

        @Override
        public FileStoreSpaceAttributes readAttributes()
            throws IOException
        {
            UnixFileStore fs = obj;
            if (fs == null)
                throw new IllegalStateException();
            UnixPath file = fs.file();

            SecurityManager sm = System.getSecurityManager();
            if (sm != null) {
                sm.checkRead(file.getPathForPermissionCheck());
                sm.checkPermission(new RuntimePermission("getFileStoreAttributes"));
            }
            final UnixFileStoreAttributes attrs;
            try {
                attrs = UnixFileStoreAttributes.get(file.getPathForSysCalls());
            } catch (UnixException x) {
                x.rethrowAsIOException(file);
                return null;    // keep compile happy
            }

            return new FileStoreSpaceAttributes() {
                @Override
                public long totalSpace() {
                    return attrs.blockSize() * attrs.totalBlocks();
                }
                @Override
                public long usableSpace() {
                    return attrs.blockSize() * attrs.availableBlocks();
                }
                @Override
                public long unallocatedSpace() {
                    return attrs.blockSize() * attrs.freeBlocks();
                }
            };
        }
    }

    // -- fstypes.properties --

    private static final Object loadLock = new Object();
    private static volatile Properties props;

    enum FeatureStatus {
        PRESENT,
        NOT_PRESENT,
        UNKNOWN;
    }

    /**
     * Returns status to indicate if file system supports a given feature
     */
    FeatureStatus checkIfFeaturePresent(String feature) {
        if (props == null) {
            synchronized (loadLock) {
                if (props == null) {
                    props = AccessController.doPrivileged(
                        new PrivilegedAction<Properties>() {
                            @Override
                            public Properties run() {
                                return loadProperties();
                            }});
                }
            }
        }

        String value = props.getProperty(type());
        if (value != null) {
            String[] values = value.split("\\s");
            for (String s: values) {
                s = s.trim().toLowerCase();
                if (s.equals(feature)) {
                    return FeatureStatus.PRESENT;
                }
                if (s.startsWith("no")) {
                    s = s.substring(2);
                    if (s.equals(feature)) {
                        return FeatureStatus.NOT_PRESENT;
                    }
                }
            }
        }
        return FeatureStatus.UNKNOWN;
    }

    private static Properties loadProperties() {
        Properties result = new Properties();
        String fstypes = System.getProperty("java.home") + "/lib/fstypes.properties";
        FileRef file = Path.get(fstypes);
        try {
            ReadableByteChannel rbc = file.newSeekableByteChannel();
            try {
                result.load(Channels.newReader(rbc, "UTF-8"));
            } finally {
                rbc.close();
            }
        } catch (IOException x) {
        }
        return result;
    }
}
